import axios from "axios";
import { omit } from "lodash-es";
import { RequestCookies } from "next/dist/compiled/@edge-runtime/cookies";
// 引入 Next.js 的路由导航
import { redirect } from "next/navigation";

export const baseUrl =
  process.env.NODE_ENV === "development"
    ? "http://localhost:3000"
    : "http://112.124.2.167:3000";
// 创建自定义的 axios 实例类型，它会直接返回响应数据而不是 AxiosResponse
const axiosInstance = axios.create({
  baseURL: baseUrl,
});

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取 token
    if (typeof window !== "undefined") {
      // 确保在浏览器环境
      const token = localStorage.getItem("token");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      // 设置User-Agent，但是实际上不需要设置，浏览器会自己携带
      // const agent = window.navigator;
      // config.headers["User-Agent"] = agent.userAgent;
      // @ts-expect-error 这里是自定义的服务器传参
    } else if (config?.next) {
      // @ts-expect-error 这里是自定义的服务器传参
      const { cookies, headers } = config.next as {
        cookies: RequestCookies;
        headers: Headers;
      };

      // 获取cookie
      const token = cookies.get("token");
      if (token) {
        config.headers.Authorization = `Bearer ${token.value}`;
      }
      // 把其他headers也加在上面
      const newHeaders = omit(Object.fromEntries(headers), ["content-type"]);
      for (const key in newHeaders) {
        config.headers[key] = newHeaders[key];
      }
      // 处理IP
      // 在转发请求时添加 IP
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 如果响应状态码是 401，跳转到登录页面
    if (error.response && error.response.status === 401) {
      console.log("经过这里");
      if (typeof window === "undefined") {
        console.error("服务端重定向了亲");
        redirect("/customer/login");
      } else {
        window.location.href = "/customer/login";
      }
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
